package com.shop.user.service.menu.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shop.user.constants.Constants;
import com.shop.user.dao.SysMenuMapper;
import com.shop.user.model.SysMenu;
import com.shop.user.service.menu.IMenuService;
import com.shop.user.vo.menu.MenuVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 根据上级菜单id获得菜单的树信结构
     * @param parentId
     * @return
     */
    @Override
    public List<MenuVo> findMenuTree(String parentId){
        LambdaQueryWrapper<SysMenu> query = new LambdaQueryWrapper<>();
        query.eq(SysMenu::getParentId,parentId);
        query.orderByAsc(SysMenu::getSortNum);
        List<SysMenu> menuList  = sysMenuMapper.selectList(query);
        if(CollUtil.isEmpty(menuList)){
            return Collections.EMPTY_LIST;
        }
        List<MenuVo> menuVoList = new ArrayList<>(menuList.size());
        MenuVo menuVo = null;
        for(SysMenu menu:menuList){
            menuVo = new MenuVo();
            BeanUtils.copyProperties(menu,menuVo);
            menuVo.setSubList(findMenuTree(menu.getId()));
            menuVoList.add(menuVo);
        }
        return menuVoList;
    }

    /**
     * 查询菜单权限信息
     * @param parentId
     * @return
     */
    @Override
    public List<String> findMenuPermission(String parentId)
    {
        LambdaQueryWrapper<SysMenu> query = new LambdaQueryWrapper<>();
        query.eq(SysMenu::getParentId,parentId);
        query.eq(SysMenu::getDataStts, Constants.DataStts.ENABLED);
        List<SysMenu> menuList  = sysMenuMapper.selectList(query);
        if(CollUtil.isEmpty(menuList)){
            return Collections.EMPTY_LIST;
        }
        List<String> permissionList = new ArrayList<>();
        MenuVo menuVo = null;
        for(SysMenu menu:menuList){
            menuVo = new MenuVo();
            BeanUtils.copyProperties(menu,menuVo);
            permissionList.add(menu.getPermission());
            permissionList.addAll(findMenuPermission(menu.getId()));
        }
        return permissionList;

    }

}
